package com.gong.gongcloudpicture1.aop;


import com.gong.gongcloudpicture1.annotation.AuthCheck;
import com.gong.gongcloudpicture1.exception.BusinessException;
import com.gong.gongcloudpicture1.exception.ErrorCode;
import com.gong.gongcloudpicture1.model.enums.UserRoleEnum;
import com.gong.gongcloudpicture1.model.vo.user.UserLoginVo;
import com.gong.gongcloudpicture1.service.UserService;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

/**
 * 权限校验aop切面类
 */
@Aspect //该注解表示当前类是一个切面类
@Component //该注解表示这是一个Spring Boot 的bean, 让Spring来加载
public class AuthInterceptor {


    @Resource
    private UserService userService;


    /**
     * 注解拦截
     * @param joinPoint
     * @return
     * @throws Throwable
     */
    //环绕通知
    //这里需要用@annotation, 值就给创建的注解, 这样才会识别成切点, 进一步做权限校验
    @Around("@annotation(authCheck)")
    public Object doInspector(ProceedingJoinPoint joinPoint, AuthCheck authCheck) throws Throwable {
        //得到注解的值
        String mastRole = authCheck.mastRole();
        //获取当前登录用户的信息
        //通过全局的上下文来来获取RequestContextHolder.currentRequestAttributes();就能拿到当前请求的所有属性
        RequestAttributes attributes = RequestContextHolder.currentRequestAttributes();
        //强转成ServletRequestAttributes拿到HttpServletRequest
        ServletRequestAttributes requestAttributes = (ServletRequestAttributes) attributes;
        HttpServletRequest request = requestAttributes.getRequest();
        UserLoginVo userLoginVo = userService.getLogInUser(request).getData();
        UserRoleEnum mastRoleEnum = UserRoleEnum.getUserRoleEnumByValue(mastRole);
        //如果被标记的方法不需要权限, 放行
        if (mastRoleEnum == null) {
            return joinPoint.proceed();
        }
        //以下代码需要有权限才能通过
        //这里需要判断用户的权限
        UserRoleEnum userRoleEnum = UserRoleEnum.getUserRoleEnumByValue(userLoginVo.getUserRole());
        if (userRoleEnum == null) {
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR);
        }
        //要求拥有管理员权限才可放行
        if (UserRoleEnum.ADMIN.equals(mastRoleEnum) && !UserRoleEnum.ADMIN.equals(userRoleEnum)) {
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR);
        }
        //权限都通过, 放行
        return joinPoint.proceed();
    }


}
